/**
 * 基金概览
 * @author gf
 */
import LittleTitle from "@/components/Title/littleTitle";
import UploadFileModal from "@/components/UploadFileModal";
import { getUrlParam } from "@/utils/utils";
import { Input, message, Spin, Table } from "antd";
import dayjs from 'dayjs';
import { useEffect, useState } from "react";
import {
  fund_earnings,
  getFundInfo,
  getFundOverview,
  analysisIndex,
} from "../../portfolio";
import styles from "./index.less";
import cn from "classnames";
import * as _ from "lodash";
import styled from "styled-components";
import CusDatePicker from "@/components/Picker/datePicker";
import EventLine from "@/components/EchartsComponents/Line/EventLine";
import icon_fund_note from "@/assets/icons/icon-fund-note.png";
import icon_edit from "@/assets/icons/icon-review.png";
import { toFixedTwo } from "../..";
import { saveRemark } from "../../portfolio";
import CustomizeRadio from "@/components/CustomizeRadio";
import LineAndBar, {
  DataProps,
} from "@/components/EchartsComponents/LineAndBar";
import MultiLine from "@/components/EchartsComponents/Line/MultiLine";
import Area from "@/components/EchartsComponents/Area";
import { getBaseColors, getExpandColors } from "@/utils/echarts";
import EventEmpty from "@/components/FOF/EventEmpty";

const LabelText = styled.div`
  color: #35425e;
  margin-right: 30px;
  &::before {
    content: "";
    display: inline-block;
    width: 2px;
    height: 10px;
    background: #e89a68;
    position: relative;
    top: 1px;
  }
  > b {
    font-weight: bold;
    padding-left: 10px;
  }
  > span {
    font-weight: 400;
  }
`;
interface FundOverviewRecord {
  visible: boolean;
  toggleModal: (bool: boolean) => void;
  fundInfo: any;
  changeRemark: (s: string) => void;
  canSetRemark: boolean; //编辑备注权限
}

type FundInfo = {
  fundEstablistDate: string;
  netValue: null | number;
  unitNV: null | number;
  fundExpireDate: string | null;
};

const CHART_RADIO = [
  {
    label: "久期分析",
    value: "1",
  },
  {
    label: "行业配置(预测)",
    value: "2",
  },
  {
    label: "资产配置(预测)",
    value: "3",
  },
  {
    label: "货基偏离度",
    value: "4",
  },
];

const XAXIS = ["分类一", "分类二", "分类三", "分类四", "分类五", "分类六"];

const RADIO_DATA = {
  1: {
    xaxis: XAXIS,
    yaxis: [
      "根据利率风险测算久期",
      "根据前五大持仓测算久期",
      "基于基金净值测算久期",
    ].map((v) => {
      return {
        label: v,
        value: XAXIS.map((m) => {
          return {
            key: m,
            value: Math.random() * 100,
          };
        }),
      };
    }),
  },
  2: {
    xaxis: XAXIS,
    yaxis: ["指标一", "指标二", , "指标三", "指标四", "指标五"].map((v) => {
      return {
        label: v,
        value: XAXIS.map((m) => {
          return {
            key: m,
            value: Math.random() * 100,
          };
        }),
      };
    }),
  },
  3: {
    xaxis: XAXIS,
    yaxis: ["指标一", "指标二", , "指标三", "指标四", "指标五"].map((v) => {
      return {
        label: v,
        value: XAXIS.map((m) => {
          return {
            key: m,
            value: Math.random() * 100,
          };
        }),
      };
    }),
  },
  4: {
    xaxis: XAXIS,
    yaxis: ["指标一", "指标二", , "指标三", "指标四", "指标五"].map((v) => {
      return {
        label: v,
        value: XAXIS.map((m) => {
          return {
            key: m,
            value: Math.random() * 100,
          };
        }),
      };
    }),
  },
};

export type TableColumnRecord = {
  title: string;
  dataIndex: string;
  key: string;
  width: number | string;
  render?: any;
  ellipsis?: boolean;
};

const FundOverview = (props: FundOverviewRecord) => {
  const { fundInfo, visible, toggleModal, changeRemark, canSetRemark } = props;
  const [indicatorData, setIndicatorData] = useState([]);
  const [start, setStart] = useState(dayjs(Date.now()).subtract(2, "years"));
  const [end, setEnd] = useState(dayjs(Date.now()).subtract(1, "days"));
  const [info, setInfo] = useState<FundInfo>({
    fundEstablistDate: "",
    netValue: null,
    unitNV: null,
    fundExpireDate: "",
  });
  const [xAxis, setXAxis] = useState([]);
  const [legend, setLegend] = useState([]);
  const [yAxis, setYAxis] = useState([]);
  const [loadingEvent, setLoadingEvent] = useState(false);
  const [tableLeft, setTableLeft] = useState([]);

  const [tableRight, setTableRight] = useState([]);
  const [columnRight, setColumnRight] = useState<TableColumnRecord[]>();
  const [columnLeft, setColumnLeft] = useState<TableColumnRecord[]>();
  const [loadingLeftTable, setLoadingLeftTable] = useState(false);
  const [loadingRightTable, setLoadingRightTable] = useState(false);

  const [isEditNote, setIsEditNote] = useState(false);
  const [remark, setRemark] = useState(fundInfo?.remark);
  const [curRadio, setCurRadio] = useState("1");
  const [showRadioList, setShowRadioList] = useState<string[]>([]);

  // 基金概览基金基本信息
  const handleQueryInfo = () => {
    getFundInfo({
      innerCode: fundInfo?.innerCode,
    }).then((res) => {
      if (res?.code === "0") {
        setInfo(res?.data);
        if (
          dayjs(Date.now()).subtract(2, "years") <
          dayjs(res?.data?.fundEstablistDate)
        ) {
          setStart(dayjs(res?.data?.fundEstablistDate));
        }
        if (res?.data?.fundExpireDate) {
          setEnd(dayjs(res?.data?.fundExpireDate));
        }
      }
    });
  };

  //  基金概览基金与基准图表
  const handleQueryChart = () => {
    setLoadingEvent(true);
    getFundOverview({
      beginDate: dayjs(start).format("YYYY-MM-DD"),
      endDate: dayjs(end).format("YYYY-MM-DD"),
      innerCode: fundInfo?.innerCode,
    }).then((res) => {
      setLoadingEvent(false);
      if (res?.code === "0") {
        setXAxis(res?.data?.xaxis.map((v) => dayjs(v).format("YYYY-MM-DD")));
        res?.data?.yaxis.reverse();
        if (res?.data?.yaxis[0].label === fundInfo.secuAbbr) {
          setYAxis(res?.data?.yaxis);
          setLegend(res?.data?.yaxis.map((v) => v.label));
        } else {
          setYAxis(res?.data?.yaxis);
          setLegend(res?.data?.yaxis.map((v) => v.label));
        }
      }
    });
  };
  // 查询列表
  const handleQueryList = () => {
    setLoadingLeftTable(true);
    setLoadingRightTable(true);
    let params = {
      innerCode: fundInfo?.innerCode,
      beginDate: dayjs(start).format("YYYY-MM-DD"),
      endDate: dayjs(end).format("YYYY-MM-DD"),
    };
    const handleGenRightTable = (res) => {
      setLoadingRightTable(false);
      setLoadingLeftTable(false);
      const arr = [
        {
          title: "期间收益率",
          base: "",
          fund: "",
          order: "",
        },
        {
          title: "近3月收益",
        },
        {
          title: "近6月收益",
        },
        {
          title: "近一年收益",
        },
        {
          title: "近三年收益",
        },
        {
          title: "今年以来",
        },
      ];

      const { table, year1, year2 } = res || {};
      // console.log(table);

      if (table?.length > 0) {
        const i = 2;
        const j = 1;
        const k = 0;
        arr.forEach((v) => {
          v.base = table[i] ? table[i][v.title] : "";
          v.fund = table[k][v.title];
          v.order = table[j][v.title];
        });
        arr.push({
          title: year1,
          base: table[i] ? table[i][year1] : "",
          fund: table[k][year1],
          order: table[j][year1],
        });
        arr.push({
          title: year2,
          base: table[i] ? table[i][year2] : "",
          fund: table[k][year2],
          order: table[j][year2],
        });
        arr.push({
          title: "成立以来",
          base: table[i] ? table[i]["成立以来"] : "",
          fund: table[k]["成立以来"],
          order: table[j]["成立以来"],
        });
        // console.log(arr);

        setTableRight(arr);
      } else {
        setTableRight([]);
      }
    };
    const handleGenLeftTable = (res) => {
      const { table } = res || {};

      if (!table) {
        setTableLeft([]);
        return;
      }
      const arr = [
        {
          title: "年化收益率",
          base: "",
          fund: "",
        },
        {
          title: "年化波动率",
        },
        {
          title: "下行风险",
        },
        {
          title: "最大回撤",
        },
        {
          title: "夏普比率",
        },
        {
          title: "索提诺比率",
        },
        {
          title: "卡玛比率",
        },
        {},
        {},
      ];
      const j = 0;
      const i = 1;
      arr.forEach((v) => {
        v.base = table[i][v.title];
        v.fund = table[j][v.title];
      });
      setColumnRight([
        {
          title: "业绩指标",
          dataIndex: "title",
          key: "title",
          width: 100,
          ellipsis: true,
        },
        {
          title: table[j].name,
          dataIndex: "fund",
          key: "fund",
          ellipsis: true,
          width: 100,
          render: (text, record: any) => {
            if (
              record.title === "夏普比率" ||
              record.title === "索提诺比率" ||
              record.title === "卡玛比率"
            ) {
              return _.isNumber(text) ? text.toFixed(2) : "-";
            } else {
              return record.title ? toFixedTwo(text) : null;
            }
          },
        },
        {
          title: "同类排名",
          dataIndex: "order",
          key: "order",
          width: 100,
          render: (text, record: any) => {
            if (record.title === "成立以来") {
              return "-";
            } else {
              return text || "-";
            }
          },
        },
        {
          title: table[i]?.name || "本基金暂不设业绩比较基准",
          dataIndex: "base",
          key: "base",
          ellipsis: true,
          width: 100,
          render: (text, record: any) => {
            if (
              record.title === "夏普比率" ||
              record.title === "索提诺比率" ||
              record.title === "卡玛比率"
            ) {
              return _.isNumber(text) ? text.toFixed(2) : "-";
            } else {
              return record.title ? toFixedTwo(text) : null;
            }
          },
        },
      ]);
      setColumnLeft([
        {
          title: "业绩指标",
          dataIndex: "title",
          key: "title",
          width: 100,
          ellipsis: true,
        },
        {
          title: table[j].name,
          dataIndex: "fund",
          key: "fund",
          ellipsis: true,
          width: 100,
          render: (text, record: any) => {
            if (
              record.title === "夏普比率" ||
              record.title === "索提诺比率" ||
              record.title === "卡玛比率"
            ) {
              return _.isNumber(text) ? text.toFixed(2) : "-";
            } else {
              return record.title ? toFixedTwo(text) : null;
            }
          },
        },
        {
          title: table[i]?.name || "本基金暂不设业绩比较基准",
          dataIndex: "base",
          key: "base",
          ellipsis: true,
          width: 100,
          render: (text, record: any) => {
            if (
              record.title === "夏普比率" ||
              record.title === "索提诺比率" ||
              record.title === "卡玛比率"
            ) {
              return _.isNumber(text) ? text.toFixed(2) : "-";
            } else {
              return record.title ? toFixedTwo(text) : null;
            }
          },
        },
      ]);
      // console.log(arr);

      setTableLeft(arr);
    };

    fund_earnings(params).then((res) => {
      if (res?.code === "0") {
        handleGenRightTable(res?.data?.intervalEarningsRet);
        handleGenLeftTable(res?.data?.indicators);
      }
    });
  };

  useEffect(() => {
    // console.log(fundInfo);
  }, [visible]);

  useEffect(() => {
    handleQueryInfo();
    handleQueryAnalysisIndicator();
  }, []);

  useEffect(() => {
    handleQueryChart();
    handleQueryList();
  }, [start, end, fundInfo?.innerCode]);

  // 保存查询条件
  const handleSaveParams = (e: any, type: string) => {
    if (type === "start") {
      setStart(e);
    } else {
      setEnd(e);
    }
  };

  const tableClass = (arr: any, max?: number) =>
    cn({
      [styles.scrollTable]: true,
      hidden: arr?.length < 8,
      [styles.scrollTableFix]: max && arr?.length > max,
      [styles.empty]: _.isEmpty(arr),
      [styles.overviewStyle]: true,
    });

  // 编辑框失去焦点
  let bool = false;
  const handleOnBlur = (e) => {
    if (remark == fundInfo?.remark) {
      setIsEditNote(false);
      return;
    }
    if (!bool) {
      saveRemark({
        innerCode: fundInfo?.innerCode,
        remark: remark,
        portfolioCode: getUrlParam("id"),
      }).then((res: any) => {
        if (res?.code === "0") {
          message.success("编辑成功");
          bool = true;
          setIsEditNote(false);
          changeRemark && changeRemark(remark);
        }
      });
    }
  };

  // 编辑内容
  const handleOnChange = (e) => {
    const { value } = e.target;
    setRemark(value);
  };

  // 分析指标
  const handleQueryAnalysisIndicator = () => {
    analysisIndex({ innerCode: fundInfo?.innerCode }).then((res: any) => {
      // console.log(res);
      if (res?.code === "0") {
        RADIO_DATA["2"] = res?.data?.industryPredicted || {};
        RADIO_DATA["3"] = res?.data?.assetPredicted || {};
        if (res?.data?.durationAnalysis) {
          // console.log(res?.data?.durationAnalysis);
          // const arr = res?.data?.durationAnalysis.map((v) => {
          //   return {
          //     ...v,
          //     xaxis: v.xaxis.sort((a, b) => Date.parse(a) - Date.parse(b)),
          //     yaxis: v.yaxis.map((m) => {
          //       return {
          //         ...m,
          //         value: m.value.sort(
          //           (a, b) => Date.parse(a.key) - Date.parse(b.key)
          //         ),
          //       };
          //     }),
          //   };
          // });

          // // console.log(arr);
          RADIO_DATA["1"] = res?.data?.durationAnalysis;
        } else {
          RADIO_DATA["1"] = {};
        }
        RADIO_DATA["4"] = res?.data?.cargoFundDeviation || {};
        setShowRadioList(res.data?.displayIndicators);
        if (res.data?.displayIndicators) {
          setCurRadio(res.data?.displayIndicators[0]);
        }
      }
    });
  };

  // console.log(RADIO_DATA);

  return (
    <UploadFileModal
      visible={visible}
      toggleModal={toggleModal}
      title="基金概览"
      footerHide={true}
      modalWidth={888}
      className={styles.overviewModal}
    >
      <div>
        <div className={styles.header}>
          <div className={styles.header_secuAbbr}>
            {fundInfo?.secuAbbr || "-"} ({fundInfo?.secuCode || "-"})
          </div>
          <LabelText>
            <b>最新净值：</b>
            <span>{info.unitNV || "-"}</span>
          </LabelText>
          <LabelText>
            <b>成立时间：</b>
            <span>{info.fundEstablistDate || "-"}</span>
          </LabelText>
          <LabelText>
            <b>规模：</b>
            <span>
              {info.netValue || "-"}
              {info.netValue ? "亿" : ""}
            </span>
          </LabelText>
        </div>
        {remark || isEditNote ? (
          <div
            className={styles.header_note}
            style={{ paddingLeft: isEditNote ? 8 : 28 }}
          >
            <img src={icon_fund_note} alt="note" />
            {!isEditNote && (
              <span className={styles.header_note_text}>{remark}</span>
            )}
            {!isEditNote ? (
              canSetRemark && (
                <div
                  className={styles.header_note_btn}
                  onClick={() => setIsEditNote(!isEditNote)}
                >
                  <span>编辑</span>
                  <img src={icon_edit} alt="" />
                </div>
              )
            ) : (
              <Input
                className={styles.header_note_input}
                showCount={{
                  formatter: (info: {
                    value: string;
                    count: number;
                    maxLength?: number;
                  }) => (
                    <span>
                      {info.count}/{info.maxLength}
                    </span>
                  ),
                }}
                autoFocus
                maxLength={30}
                value={remark}
                onBlur={handleOnBlur}
                onChange={handleOnChange}
                onPressEnter={handleOnBlur}
              />
            )}
          </div>
        ) : null}
        <div className={styles.chart}>
          <div className={styles.chart_header}>
            <span className={styles.chart_header_title}>业绩走势</span>
            <div>
              <CusDatePicker
                label="时间范围"
                startValue={start}
                endValue={end}
                idName1="fundInfo-left"
                idName2="fundInfo-right"
                onChange={handleSaveParams}
                className={styles.customDatePicker}
                disabledDate={(currentDate) => {
                  return info.fundEstablistDate
                    ? dayjs(currentDate).startOf("days").valueOf() <
                        dayjs(info.fundEstablistDate).valueOf() ||
                        dayjs(currentDate).startOf("days").valueOf() >
                          dayjs(end).valueOf()
                    : dayjs(currentDate).startOf("days").valueOf() >
                        dayjs().subtract(1, "days").valueOf();
                }}
                disabledEndDate={(currentDate) => {
                  return info.fundExpireDate
                    ? dayjs(currentDate).startOf("days").valueOf() >
                        dayjs(info.fundExpireDate).valueOf() ||
                        dayjs(currentDate).startOf("days").valueOf() <
                          dayjs(start).valueOf()
                    : dayjs(currentDate).startOf("days").valueOf() >
                        dayjs().subtract(1, "days").valueOf() ||
                        dayjs(currentDate).startOf("days").valueOf() <
                          dayjs(start).valueOf();
                }}
              />
            </div>
          </div>
          <Spin spinning={loadingEvent}>
            <div className={styles.chart_body}>
              <EventLine
                idName="fund-overview-event"
                xAxis={xAxis}
                legend={legend}
                data={yAxis}
                color={["#3457C4", "#E85C36"]}
                // events={checkedEvents}
                pointLegend={fundInfo?.secuAbbr}
                percent
              />
            </div>
          </Spin>
        </div>
        <div className={styles.table}>
          <div className={styles.table_indicator}>
            <LittleTitle title="绩效指标" ml="12px" mt="0" />
            <Table
              className={cn(tableClass(indicatorData, 8))}
              columns={columnLeft}
              rowKey={(r) => r.provinceCode}
              dataSource={tableLeft}
              bordered
              scroll={indicatorData?.length > 8 ? { y: 222 } : {}}
              pagination={false}
              loading={loadingLeftTable}
            />
          </div>
          <div className={styles.table_benchmark}>
            <LittleTitle title="区间收益" ml="18px" mt="0" />
            <Table
              className={cn(tableClass(indicatorData, 8))}
              columns={columnRight}
              rowKey={(r) => r.provinceCode}
              dataSource={tableRight}
              bordered
              scroll={indicatorData?.length > 8 ? { y: 222 } : {}}
              pagination={false}
              loading={loadingRightTable}
            />
          </div>
        </div>
        {!_.isEmpty(showRadioList) && (
          <div className={styles.radioChart}>
            <div className={styles.radioChart_header}>分析指标</div>
            <CustomizeRadio
              options={CHART_RADIO.filter((v) =>
                showRadioList.includes(v.value)
              )}
              value={curRadio}
              setValue={setCurRadio}
            />
            {console.log()}
            {curRadio === "1" ? (
              <div>
                <div style={{ height: 180 }}>
                  {!RADIO_DATA[curRadio]?.rateAxis?.xaxis ? (
                    <EventEmpty
                      title="暂无数据"
                      style={{ padding: "30px 0" }}
                    />
                  ) : (
                    <LineAndBar
                      // legendStyle={legendStyle}
                      idName={`fund-overview-event-detail${curRadio}`}
                      xAxis={RADIO_DATA[curRadio]?.rateAxis?.xaxis}
                      data={
                        RADIO_DATA[curRadio]?.rateAxis?.yaxis?.length > 0
                          ? RADIO_DATA[curRadio]?.rateAxis?.yaxis
                          : []
                      }
                      legend={
                        RADIO_DATA[curRadio]?.rateAxis?.yaxis?.length > 0
                          ? RADIO_DATA[curRadio]?.rateAxis?.yaxis.map(
                              (item: DataProps) => item.label
                            )
                          : []
                      }
                      // color={["#3457C4", "#E85C36"]} //上折线指定色
                    />
                  )}
                </div>
                <div style={{ height: 180 }}>
                  {!RADIO_DATA[curRadio]?.predictedAxis?.xaxis ? (
                    <EventEmpty
                      title="暂无数据"
                      style={{ padding: "30px 0" }}
                    />
                  ) : (
                    <MultiLine
                      gridStyle={{ top: 40, left: 10 }}
                      xAxis={RADIO_DATA[curRadio]?.predictedAxis?.xaxis}
                      idName={`fund-overview-event-detail${curRadio}_2`}
                      data={
                        RADIO_DATA[curRadio]?.predictedAxis?.yaxis?.length > 0
                          ? RADIO_DATA[curRadio]?.predictedAxis?.yaxis
                          : []
                      }
                      legend={
                        RADIO_DATA[curRadio]?.predictedAxis?.yaxis?.length > 0
                          ? RADIO_DATA[curRadio]?.predictedAxis?.yaxis.map(
                              (item: DataProps) => item.label
                            )
                          : []
                      }
                      color={["#3457C4", "#E85C36"]}
                      showRightY={false}
                    />
                  )}
                </div>
              </div>
            ) : curRadio === "2" || curRadio === "3" ? (
              <div style={{ height: 180 }}>
                {!RADIO_DATA[curRadio]?.xaxis ? (
                  <EventEmpty title="暂无数据" style={{ padding: "30px 0" }} />
                ) : (
                  <Area
                    percent
                    showLine={true}
                    legendStyle={{ top: 5 }}
                    idName={`fund-overview-event-detail${curRadio}`}
                    xAxis={RADIO_DATA[curRadio].xaxis}
                    legend={
                      RADIO_DATA[curRadio]?.yaxis?.length > 0
                        ? RADIO_DATA[curRadio]?.yaxis.map(
                            (item: DataProps) => item.label
                          )
                        : []
                    }
                    data={
                      RADIO_DATA[curRadio]?.yaxis?.length > 0
                        ? RADIO_DATA[curRadio]?.yaxis
                        : []
                    }
                    color={[...getBaseColors(), ...getExpandColors()]}
                  />
                )}
              </div>
            ) : curRadio === "4" ? (
              <div style={{ height: 180 }}>
                {!RADIO_DATA[curRadio].xaxis ? (
                  <EventEmpty title="暂无数据" style={{ padding: "30px 0" }} />
                ) : (
                  <MultiLine
                    percent
                    gridStyle={{ top: 40, left: 10 }}
                    xAxis={RADIO_DATA[curRadio].xaxis}
                    idName={`fund-overview-event-detail${curRadio}_2`}
                    data={
                      RADIO_DATA[curRadio]?.yaxis?.length > 0
                        ? RADIO_DATA[curRadio]?.yaxis
                        : []
                    }
                    legend={
                      RADIO_DATA[curRadio]?.yaxis?.length > 0
                        ? RADIO_DATA[curRadio]?.yaxis.map(
                            (item: DataProps) => item.label
                          )
                        : []
                    }
                    color={[...getBaseColors(), ...getExpandColors()]}
                    showRightY={false}
                    precisionY={2}
                  />
                )}
              </div>
            ) : null}
          </div>
        )}
      </div>
    </UploadFileModal>
  );
};

export default FundOverview;
